"""import ttemplate

t = ttemplate.TTemplate('html/')
t.load('login.html')
attrs = {}
attrs['username'] = "JON"
attrs['message'] = "Some Message, WAY TO GO!!!"
t.substitute(attrs)

print t.get_html()
print
print "commands"
print t.commands"""

import re
import string

class TTemplate():
    def __init__(self, html_dir_base=''):
        """Dir base is html/"""
        self.html_dir_base = html_dir_base
        self.metadata_raw = ''
        self.commands = []
        self.defaults = {}
        self.s = ''

        
    def load(self, filename): 
        load_before = []
        load_after = []
        get_command = re.compile(r'### ([a-z_]+) (.*)$', re.I)
        
        f = open(self.html_dir_base + filename, 'r')
        line = f.readline()
        m = get_command.match(line)
        while (m):
            self.metadata_raw += line
            command = m.group(1)
            action = m.group(2)
            
            self.commands.append((command,action))
                        
            if command == 'load_before':
                load_before.append(action)
            elif command == 'load_after':
                load_after.append(action)
            elif command == 'default':
                (k,v) = action.split('=',1)
                self.defaults[k] = v
            else:
                raise Exception('Unknown command in template file (%s): %s=%s' % (filename, command, action))
            line = f.readline()
            m = get_command.match(line)

        # Load all files before this one 
        for fname in load_before:
            self.load(fname)
        # Finish loading this file  
        self.s += line
        for line in f.readlines():
            self.s += line
        # Load all the remaining files
        for fname in load_after:
            self.load(fname)
    
    def add_defaults(self,attrs):
        for (k,v) in attrs.items():
            self.defaults[k] = v
            
    def substitute(self,attrs):
        for k in self.defaults.keys():
            if k not in attrs:
                attrs[k] = self.defaults[k]
        self.s = string.Template(self.s).safe_substitute(attrs)
    
    def get_html(self):
        return self.s
        
        

            
            
            